<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>共用图例的双饼图联动</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .container {
            display: flex;
            flex-direction: column;
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }

        .legend-container {
            text-align: center;
            margin-bottom: 20px;
        }

        .charts-wrapper {
            display: flex;
            gap: 20px;
        }

        .chart {
            flex: 1;
            min-width: 0;
        }

        #chart1,
        #chart2 {
            width: 100%;
            height: 400px;
        }

        .chart-title {
            text-align: center;
            font-size: 16px;
            font-weight: bold;
            margin-top: 10px;
            color: #333;
        }

        .export-btn {
            color: #1890ff;
            margin-left: 10px;
            font-weight: normal;
            cursor: pointer;
        }

        .legend-item {
            display: inline-block;
            margin: 0 15px;
            cursor: pointer;
            padding: 5px 10px;
            border-radius: 4px;
            transition: all 0.3s;
        }

        .legend-item:hover {
            background-color: #f0f0f0;
        }

        .legend-color {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 6px;
            margin-right: 5px;
            vertical-align: middle;
        }

        .legend-item.inactive {
            opacity: 0.5;
            text-decoration: line-through;
        }

        @media (max-width: 768px) {
            .charts-wrapper {
                flex-direction: column;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 共用图例容器 -->
        <div class="legend-container" id="sharedLegend"></div>

        <div class="charts-wrapper">
            <div class="chart">
                <div id="chart1"></div>
                <div class="chart-title">
                    数量
                    <span class="export-btn" onclick="exportChart(1)">导出</span>
                </div>
            </div>
            <div class="chart">
                <div id="chart2"></div>
                <div class="chart-title">
                    面积
                    <span class="export-btn" onclick="exportChart(2)">导出</span>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 初始化图表
        const chart1 = echarts.init(document.getElementById('chart1'));
        const chart2 = echarts.init(document.getElementById('chart2'));

        // 颜色配置
        const colorPalette = ['#5470C6', '#91CC75', '#FAC858', '#EE6666'];

        // 数据定义
        const categories = ['更新意愿未定', '其他地块', '其他地块', '有更新意愿或计划'];

        // 图表数据
        const chartData = {
            quantity: [1048, 735, 580, 484], // 数量数据
            amount: [52.4, 22.0, 17.4, 14.5]  // 金额数据
        };

        // 当前选中状态
        let selectedState = {};
        categories.forEach(category => {
            selectedState[category] = true; // 默认全部选中
        });

        // 创建自定义图例
        function createSharedLegend() {
            const legendContainer = document.getElementById('sharedLegend');
            legendContainer.innerHTML = '';

            categories.forEach((category, index) => {
                const legendItem = document.createElement('div');
                legendItem.className = `legend-item ${selectedState[category] ? '' : 'inactive'}`;
                legendItem.dataset.category = category;

                // 图例颜色标记
                const colorMarker = document.createElement('span');
                colorMarker.className = 'legend-color';
                colorMarker.style.backgroundColor = colorPalette[index];

                // 图例文本
                const text = document.createTextNode(category);

                legendItem.appendChild(colorMarker);
                legendItem.appendChild(text);
                legendContainer.appendChild(legendItem);

                // 添加点击事件
                legendItem.addEventListener('click', function () {
                    toggleSeries(category);
                });
            });
        }

        // 切换系列显示状态
        function toggleSeries(category) {
            // 切换选中状态
            selectedState[category] = !selectedState[category];

            // 更新两个图表
            updateChartSelection(chart1);
            updateChartSelection(chart2);

            // 更新图例样式
            updateLegendStyle(category);
        }

        // 更新图表选中状态
        function updateChartSelection(chart) {
            const option = chart.getOption();

            // 修复：使用更可靠的方式获取数据属性
            option.series.forEach(series => {
                // 根据系列名称映射到正确的数据属性
                const dataKey = series.name.includes('数量') ? 'quantity' : 'amount';

                series.data = categories
                    .filter(name => selectedState[name])
                    .map((name, index) => ({
                        name,
                        value: chartData[dataKey][categories.indexOf(name)]
                    }));
            });

            chart.setOption(option);
        }

        // 更新图例样式
        function updateLegendStyle(category) {
            const legendItem = document.querySelector(`.legend-item[data-category="${category}"]`);
            if (legendItem) {
                legendItem.classList.toggle('inactive', !selectedState[category]);
            }
        }

        // 初始化图表配置
        function initCharts() {
            // 图表1配置 - 数量
            const option1 = {
                color: colorPalette,
                title: {
                    text: '销售数量占比',
                    subtext: '单位：件',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                series: [{
                    name: '销售数量',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '18',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: categories.map((name, index) => ({
                        name,
                        value: chartData.quantity[index]
                    }))
                }]
            };

            // 图表2配置 - 金额
            const option2 = {
                color: colorPalette,
                title: {
                    text: '销售金额占比',
                    subtext: '单位：万元',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                series: [{
                    name: '销售金额',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '18',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: categories.map((name, index) => ({
                        name,
                        value: chartData.amount[index]
                    }))
                }]
            };

            chart1.setOption(option1);
            chart2.setOption(option2);
        }

        // 初始化
        function init() {
            initCharts();
            createSharedLegend();

            // 响应式调整
            window.addEventListener('resize', function () {
                chart1.resize();
                chart2.resize();
            });
        }
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>

</html>